<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form" v-if="headerShow">
        <a-form size="small" :model="pageData" layout="inline">
          <a-form-item label="报修单号">
            <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder="" v-model="dropDownData"
              @press-enter="huiche" />
          </a-form-item>
          <a-form-item label="报修日期">
            <a-date-picker popup-container="html" class="bacClass" v-model="dropDownData2"
              style="width: 200px" />至<a-date-picker popup-container="html" class="bacClass" v-model="dropDownData3"
              style="width: 200px" />
          </a-form-item>
          <a-form-item label="报修部门">
            <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder="" v-model="dropDownData4"
              @press-enter="huiche" />
          </a-form-item>
          <a-form-item label="报修员工">
            <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder="" v-model="dropDownData5"
              @press-enter="huiche" />
          </a-form-item>
        </a-form>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <Toolbar :items="toolbarList" @select="selectHandler" @dispatch="dispatchs"> </Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <a-tabs   :lazy-load="true" :justify="true" @change="tabChanges">
        <a-tab-pane :key="1" title="未派工">
          <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
            <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple"
              @grid-ready="gridReady" style="height: calc(100% - 45px)" :defaultColDef="defaultColDef" class="ag-theme-alpine"
              :rowData="tableDataList" :columnDefs="tc" :localeText="localeText1" @columnResized="onColumnResized"
              @columnMoved="onColumnMoved">
            </AgGridVuesCopys>
            <paginationCopys :page-size-options="pagingList1" :total="fySelet.total" show-total show-jumper show-page-size
              @change="PageSize" @page-size-change="change" style="justify-content: center" :page-size="fySelet.size" :current="fySelet.page" />
          </a-spin>
        </a-tab-pane>
        <a-tab-pane :key="2" title="已派工">
          <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
            <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple"
              @grid-ready="gridReady2" style="height:calc(100% - 45px)" :defaultColDef="defaultColDef" class="ag-theme-alpine"
              :rowData="tableDataList2" :columnDefs="tc2" :localeText="localeText1" @columnResized="onColumnResized2"
              @columnMoved="onColumnMoved2">
            </AgGridVuesCopys>
            <paginationCopys :page-size-options="pagingList1" :total="fySelet2.total" show-total show-jumper
              show-page-size @change="PageSize2" @page-size-change="change2" style="justify-content: center"
              :page-size="fySelet2.size" :current="fySelet2.page"/>
          </a-spin>
        </a-tab-pane>
      </a-tabs>
    </template>

    <a-modal :width="800" v-model:visible="visible" :on-before-ok="handleOk" @cancel="() => (visible = false)"
      :mask-closable="false">
      <template #title>
        {{ sideTitle }}
      </template>
      <a-form ref="formRef" :model="dataForm">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="员工姓名" field="keepStaff" label-col-flex="80px"
              :rules="[{ required: true, message: '员工姓名必填' }]" :validate-trigger="['change', 'blur']">
              <a-select popup-container="html" :disabled="pageData.sideTitle == '派工详情'" class="bacClass"
                :default-value="dataForm.keepStaff" :style="{ width: '250px' }" multiple v-model="dataForm.keepStaff"
                allow-clear allow-search>
                <a-option v-for="item in wxYgList" :value="item.id + '-' + item.name">{{ item.name }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="开始时间" label-col-flex="80px" field="beginTime"
              :rules="[{ required: true, message: '报修时间必填' }]" :validate-trigger="['change', 'blur']">
              <a-date-picker popup-container="html" :disabled="pageData.sideTitle == '派工详情'" class="bacClass"
                style="width: 250px" v-model="dataForm.beginTime" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="维修状态" field="keepType" label-col-flex="80px">
              <a-select popup-container="html" class="bacClass" disabled v-model="dataForm.workersState"
                style="width: 250px">
                <a-option :value="1">维修中</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="维修类型" label-col-flex="80px" field="workersState"
              :rules="[{ required: true, message: '维修状态必填' }]" :validate-trigger="['change', 'blur']">
              <a-select popup-container="html" class="bacClass" :disabled="pageData.sideTitle == '派工详情'"
                v-model="dataForm.keepType" style="width: 250px">
                <a-option value="1">厂内直接维修</a-option>
                <a-option value="2">厂内采购配件维修</a-option>
                <a-option value="3">外发维修</a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </pageTabelLayout>
</template>

<script setup lang="ts">
import { post, get } from '@/api/http'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'

import { Message, Modal } from '@arco-design/web-vue'
import { pagingList } from '@/api/paging'
import { localeText } from '@/api/aggridZw'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
import { saveOrUpdateGridState as saveOrUpdateGridState02 } from '@/hooks/useGridState'

const headerShow = ref(true)

const pageData: any = reactive({
  dropDownData: '',
  dropDownData2: '',
  dropDownData3: '',
  dropDownData4: '',
  dropDownData5: '',
  showAdd: false,
  sideTitle: '',
  pageLoading: false,
})

const {
  dropDownData,
  dropDownData2,
  dropDownData3,
  dropDownData4,
  dropDownData5,
  showAdd,
  sideTitle,
} = toRefs(pageData)

const dataForm: any = reactive({
  id: null,
  keepStaff: '',
  keepType: 1,
  beginTime: '',
  workersState: null,
  keepStaffId: '',
})

const tablesId: any = ref(1)

const toolbarList: any = ref(['查询', '派工'])

const tabChanges = (e: any) => {
  tablesId.value = e
  if (e == 1) {
    toolbarList.value = ['查询', '派工']
    fySelet.page = 1
    selectList()
  } else if (e == 2) {
    toolbarList.value = ['查询']
    fySelet2.page = 1
    selectList2()
  }
}

onMounted(() => {
  selectList()
})

function selectList() {
  pageData.pageLoading = true
  updateGridState01()
  post({
    url: 'temRepair/repairSubscribe/findRepairSubscribePage',
    data: {
      page: fySelet.page,
      limit: fySelet.size,
      repairCode: pageData.dropDownData,
      repairDep: pageData.dropDownData4,
      repairStaff: pageData.dropDownData5,
      repairTime: pageData.dropDownData2,
      repairTime2: pageData.dropDownData3,
      judgeState: 1,
      workersState: 0,
    },
  })
    .then((res: any) => {
      gridOption.value.setRowData(res.data.list)
      fySelet.total = res.data.total
    })
    .catch(console.log)
    .finally(() => {
      pageData.pageLoading = false
    })
}

function selectList2() {
  pageData.pageLoading = true
  updateGridState02()
  post({
    url: 'temRepair/repairSubscribe/findRepairSubscribePage',
    data: {
      page: fySelet2.page,
      limit: fySelet2.size,
      repairCode: pageData.dropDownData,
      repairDep: pageData.dropDownData4,
      repairStaff: pageData.dropDownData5,
      repairTime: pageData.dropDownData2,
      repairTime2: pageData.dropDownData3,
      judgeState: 1,
      workersState: 1,
    },
  })
    .then((res: any) => {
      gridOption2.value.setRowData(res.data.list)
      fySelet2.total = res.data.total
    })
    .catch(console.log)
    .finally(() => {
      pageData.pageLoading = false
    })
}

const huiche = () => {
  if (tablesId.value == 1) {
    selectList()
  } else if (tablesId.value == 2) {
    selectList2()
  }
}

const selectHandler = () => {
  if (tablesId.value == 1) {
    fySelet.page = 1
    selectList()
  } else if (tablesId.value == 2) {
    fySelet2.page = 1
    selectList2()
  }
}

const options: any = ref([])
const options2: any = ref([])

const tableDataList: any = ref([])
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
  colState.value = params.columnApi
}
const tableDataList2: any = ref([])
const gridOption2 = ref()
const colState2 = ref()
const gridReady2 = (params: any) => {
  gridOption2.value = params.api
  colState2.value = params.columnApi
}
const defaultColDef = {
  sortable: true,
  resizable: true,
  filter: true,
}

const fySelet: any = reactive({
  total: 10,
  size: 10,
  page: 1,
})

const PageSize = (val: any) => {
  fySelet.page = val
  selectList()
}

const change = (val: any) => {
  fySelet.size = val
  selectList()
}

const fySelet2: any = reactive({
  total: 10,
  size: 10,
  page: 1,
})

const PageSize2 = (val: any) => {
  fySelet2.page = val
  selectList2()
}

const change2 = (val: any) => {
  fySelet2.size = val
  selectList2()
}

const tc = [
  {
    showRowGroup: 'hide_def',
    headerName: '',
    checkboxSelection: true,
    headerCheckboxSelection: true,
    pinned: 'left',
    width: 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: 'left',
  },
  {
    headerName: '报修单号',
    field: 'repairCode',
    // pinned: o['fixed'],
    width: 150,
  },
  {
    headerName: '报修时间',
    field: 'repairTime',
    width: 150,
  },
  {
    headerName: '报修部门',
    field: 'repairDep',
    width: 150,
  },
  {
    headerName: '报修员工',
    field: 'repairStaff',
    width: 150,
  },
  {
    headerName: '设备编号',
    field: 'facilityCode',
    width: 150,
  },
  {
    headerName: '设备名称',
    field: 'facilityName',
    width: 150,
  },
  {
    headerName: '设备类型',
    field: 'facilityType',
    width: 150,
  },
  {
    headerName: '维修部门',
    field: 'maintainDep',
    width: 150,
  },
  // {
  //     headerName: '维修部门负责人',
  //     field: 'maintainDepStaff',
  //     width: 150
  // },
  {
    headerName: '报修说明',
    field: 'repairRemark',
    width: 150,
  },
  {
    headerName: '设备故障描述',
    field: 'facilityHitchcause',
    width: 150,
  },
]

const tc2 = [
  {
    showRowGroup: 'hide_def',
    headerName: '',
    checkboxSelection: true,
    headerCheckboxSelection: true,
    pinned: 'left',
    width: 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: 'left',
  },
  {
    headerName: '报修单号',
    field: 'repairCode',
    // pinned: o['fixed'],
    width: 150,
  },
  {
    headerName: '报修时间',
    field: 'repairTime',
    width: 150,
  },
  {
    headerName: '报修部门',
    field: 'repairDep',
    width: 150,
  },
  {
    headerName: '报修员工',
    field: 'repairStaff',
    width: 150,
  },
  {
    headerName: '设备编号',
    field: 'facilityCode',
    width: 150,
  },
  {
    headerName: '设备名称',
    field: 'facilityName',
    width: 150,
  },
  {
    headerName: '设备类型',
    field: 'facilityType',
    width: 150,
  },
  {
    headerName: '维修部门',
    field: 'maintainDep',
    width: 150,
  },
  // {
  //     headerName: '维修部门负责人',
  //     field: 'maintainDepStaff',
  //     width: 150
  // },
  {
    headerName: '报修说明',
    field: 'repairRemark',
    width: 150,
  },
  {
    headerName: '设备故障描述',
    field: 'facilityHitchcause',
    width: 150,
  },
  {
    headerName: '状态',
    field: 'completeState',
    pinned: 'right',
    width: 150,
    filter: true,
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == 0 ? '未完工' : params.value == 1 ? '已完工' : ''
      },
    },
    cellRenderer: {
      template: `
            <el-tag type="success" v-if="states == 0">未完工</el-tag>
            <el-tag type="warning"  v-if="states == 1">已完工</el-tag>
            `,
      setup(props: any) {
        return {
          states: props.params.data.completeState,
        }
      },
    },
  },
  {
    headerName: '操作',
    field: 'slot',
    pinned: 'right',
    width: 160,
    cellRenderer: {
      template: `
            <a-space>
                <a-tag class="tagCss" v-if="states == 0" @click="a" >修 改</a-tag>
                <a-tag class="tagCss" @click="b">详 情</a-tag>
            </a-space>
            `,
      setup(props: any) {
        const a = () => {
          updateList(props.params.data, 1) // props.params.data
        }
        const b = () => {
          updateList(props.params.data, 2) // props.params.data
        }
        return {
          a,
          b,
          states: props.params.data.completeState,
        }
      },
    },
  },
]

const updateList = (e: any, num: any) => {
  dataForm.keepType = e.keepType
  dataForm.workersState = e.workersState
  dataForm.beginTime = e.beginTime
  dataForm.keepStaff = []
  dataForm.id = e.id
  e.keepStaff.split(',').forEach((v: any, index: any) => {
    dataForm.keepStaff.push(e.keepStaffId.split(',')[index] + '-' + v)
  })
  if (num == 1) {
    post({
      url: 'org/hrEmployee/getList',
      data: {
        deleteState: 0,
        obsoleteState: 0,
        department_id: e.maintainDepID,
      },
    }).then((res: any) => {
      if (res.code == 200) {
        wxYgList.value = res.data
        dataForm.workersState = 1
        pageData.sideTitle = '修改派工'
        visible.value = true
      }
    })
  } else if (num == 2) {
    pageData.sideTitle = '派工详情'
    visible.value = true
  }
}

const wxYgList: any = ref([])

const dispatchs = () => {
  pageData.sideTitle = '派工'
  for (let i in dataForm) {
    dataForm[i] = null
  }
  post({
    url: 'org/hrEmployee/getList',
    data: {
      deleteState: 0,
      obsoleteState: 0,
      department_id: gridOption.value.getSelectedRows()[0].maintainDepID,
    },
  }).then((res: any) => {
    if (res.code == 200) {
      wxYgList.value = res.data
      dataForm.workersState = 1
      visible.value = true
    }
  })
}

const visible: any = ref(false)

const formRef: any = ref()

const handleOk = async () => {
  const err = await formRef.value?.validate()
  if (!err) {
    let wxYgString = ''
    let wxYgStringId = ''
    dataForm.keepStaff.forEach((e: any, index: any) => {
      if (index == dataForm.keepStaff.length - 1) {
        wxYgString = wxYgString + e.split('-')[1]
        wxYgStringId = wxYgStringId + e.split('-')[0]
      } else {
        wxYgString = wxYgString + e.split('-')[1] + ','
        wxYgStringId = wxYgStringId + e.split('-')[0] + ','
      }
    })
    if (pageData.sideTitle == '派工') {
      const res = await post({
        url: 'temRepair/repairSubscribe/updateRepairSubscribe',
        data: gridOption.value.getSelectedRows().map((o: any) => {
          return {
            id: o.id,
            keepStaff: wxYgString,
            keepStaffId: wxYgStringId,
            keepType: dataForm.keepType,
            beginTime: dataForm.beginTime,
            workersState: dataForm.workersState,
          }
        }),
      })
      if (res.code == 200) {
        Message.success('成功')
        selectList()
        selectList2()
        return true
      }
    } else {
      const res = await post({
        url: 'temRepair/repairSubscribe/updateRepairSubscribe',
        data: [
          {
            id: dataForm.id,
            keepStaff: wxYgString,
            keepStaffId: wxYgStringId,
            keepType: dataForm.keepType,
            beginTime: dataForm.beginTime,
            workersState: dataForm.workersState,
          },
        ],
      })
      if (res.code == 200) {
        Message.success('成功')
        selectList()
        selectList2()
        return true
      }
    }
  } else {
    return false
  }
}

const localeText1: any = ref(localeText)
const pagingList1: any = ref(pagingList)
const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
  saveOrUpdateGridState01('EquipmentMaintenanceList002', gridOption, colState, tc)
const onColumnMoved = () => {
  saveGridState01()
}
const onColumnResized = () => {
  saveGridState01()
}
const { saveGridState: saveGridState02, updateGridState: updateGridState02 } =
  saveOrUpdateGridState02('EquipmentMaintenanceList002s', gridOption2, colState2, tc2)
const onColumnMoved2 = () => {
  saveGridState02()
}
const onColumnResized2 = () => {
  saveGridState02()
}
</script>
<style scoped lang="less">
:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}
</style>
